const bcrypt = require("bcryptjs");

const { getUserInfo } = require("../service/user.service");
const { userAlreadyExited, userFormateError, userRegisterError, userDoesNotExist, userLoginError, invalidPassword, euqulToPwd, notGetPwd } = require("../constant/err.type");

//用户名判空验证
const userValidator = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;
  if (!user_name || !password) {
    console.error("用名或密码为: ", ctx.request.body);
    ctx.app.emit("error", userFormateError, ctx);
    return;
  }
  await next(); //交由下一个中间件进行处理
};

// 用户名存在验证
const verifyUser = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;

  try {
    const res = await getUserInfo({ user_name });
    if (res) {
      console.error("用户名已经存在", { user_name });
      ctx.app.emit("error", userAlreadyExited, ctx); //提交错误处理
      return;
    }
  } catch (error) {
    ctx.app.emit("error", userRegisterError, ctx);
    return;
  }
  await next(); //交由下一个中间件进行处理
};

// 密码加密
const crpytPassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  const salt = bcrypt.genSaltSync(10);
  // hash 保存的是密码密文
  const hash = bcrypt.hashSync(password, salt);
  ctx.request.body.password = hash;

  await next();
};

// 判断用户登录校验
const verifyLogin = async (ctx, next) => {
  // 1.根据用户名,查询数据库,判断用户是否存在
  const { user_name, password } = ctx.request.body;

  try {
    const res = await getUserInfo({ user_name });
    if (!res) {
      ctx.app.emit("error", userDoesNotExist, ctx); //用户不存在
      return;
    }
    // 2.密码是否匹配（不匹配：报错）
    if (!bcrypt.compareSync(password, res.password)) {
      ctx.app.emit("error", invalidPassword, ctx); //用户密码错误
      return;
    }
  } catch (error) {
    ctx.app.emit("error", userLoginError, ctx); //用户登录失败
    return;
  }
  await next();
};

// 判断两次修改的密码,是否相同
const equalToPassword = async (ctx, next) => {
  const newPassword = ctx.request.body.password ? ctx.request.body.password : null; //密码明文
  // console.log("密码字段: ", newPassword);
  const oldPassword = ctx.state.user.password; //加密的密文

  if (!newPassword) {
    //没有传密码
    return ctx.app.emit("error", notGetPwd, ctx);
  }

  if (bcrypt.compareSync(newPassword, oldPassword)) {
    return ctx.app.emit("error", euqulToPwd, ctx);
  }

  // console.log(newPassword, oldPassword);
  // console.log(bcrypt.compareSync(newPassword, oldPassword));
  // console.log(bcrypt.compareSync("123456", oldPassword));
  await next();
};

module.exports = {
  userValidator,
  verifyUser,
  crpytPassword,
  verifyLogin,
  equalToPassword,
};
